package com.ruoyi.consumer.controller;

import com.github.pagehelper.PageHelper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.IpAddressUtils;
import com.ruoyi.consumer.constance.AgentPoxyLevelEnum;
import com.ruoyi.consumer.domain.CAgentRelations;
import com.ruoyi.consumer.domain.CUser;
import com.ruoyi.consumer.mapper.AgentMapper;
import com.ruoyi.consumer.service.impl.CAgentRelationsServiceImpl;
import com.ruoyi.consumer.service.impl.CUserServiceImpl;
import com.ruoyi.consumer.utils.pay.HttpStream;
import com.ruoyi.consumer.utils.redis.AgentCache;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import static com.ruoyi.consumer.constance.AgentPoxyLevelEnum.*;

@Api(tags = "代理关系")
@RestController
@RequestMapping("/api/agency")
public class AgencyController {


    @Autowired
    private RedisCache redisCache;

    @Autowired
    private CAgentRelationsServiceImpl agentRelationsService;

    @Autowired
    private AgentMapper agentMapper;

    @Autowired
    private AgentCache agentCache;

    @Autowired
    private CUserServiceImpl userService;


    @ApiOperation("生成我的邀请码")
    @RequestMapping("/getMyYqm")
    public AjaxResult getMyYqm(String userId) {
        String s = YqmGenerate(userId, "yqm");
        return AjaxResult.success("生成邀请码" + s);
//        AjaxResult ajaxResult = new AjaxResult();
//        //首先判断该用户已有邀请码
//        DailiYqm yqm = new DailiYqm();
//        yqm.setDailiId(userId);
//        List<DailiYqm> list = dailiYqmService.selectDailiYqmList(yqm);
//        if (list.size() > 0) {
//            ajaxResult.put("msg", "存在邀请二维码");
//            ajaxResult.put("data", list.get(0));
//        } else {
//            String url = YqmGenerate(userId);
//        }
//
//        ajaxResult.put("yqm", getMyYqm(userId));
//        return ajaxResult;
    }

    @ApiOperation("生成我的邀请码")
    @RequestMapping("/genSnQRCode")
    public AjaxResult genSnQRCode(String sn) {
        String s = YqmGenerate(sn, "sn");
        return AjaxResult.success(s);
    }

    //生成我的邀请码
    public String YqmGenerate(String userId, String path) {
        String Path = "/home/ruoyi/uploadPath/upload/" + path + "/" + userId + ".png";
        String params = "{\"scene\":\"" + path + "Id=" + userId + "\"}";
        byte[] data = HttpStream.post("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + redisCache.getCacheObject("token:" + "findConsumerAccessToken"), params);
        File imageFile = new File(Path);
        //创建输出流
        FileOutputStream outStream = null;
        try {
            outStream = new FileOutputStream(imageFile);
            //写入数据
            outStream.write(data);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                //关闭输出流
                outStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return IpAddressUtils.getAddressInfo() + "/profile/upload/yqm/" + userId + ".png";
    }


    /**
     * 申请成为代理
     *
     * @param userId
     * @param superiorId
     * @param agentId
     * @return
     */
    @ApiOperation("申请成为代理")
    @GetMapping("/applyAgency")
    public AjaxResult applyAgency(@ApiParam(value = "用户id", required = true) Integer userId,
                                  @ApiParam(value = "上级用户id", required = true) Integer superiorId,
                                  @ApiParam(value = "代理表id", required = true) Integer agentId) {

        Assert.notNull(userId, "用户id不能为空");
        Assert.notNull(superiorId, "上级用户id不能为空");
        Assert.notNull(agentId, "代理表id不能为空");
        CUser cUser = userService.selectCUserByUserId(userId);
        Assert.notNull(cUser, "申请者用户信息不存在");

        //首先判断该用户是否已经是代理
        Integer count = agentMapper.isAgentPathHasId(userId);
        System.out.println("userIdisAgentPathHasId==============" + count);
        if (count != null && count > 0) {
            List<String> list = agentMapper.isNewUser(userId);
            System.out.println(list);
            if (list.size() > 0) {
                for (String s : list) {
                    System.out.println(s);
                    if (s.equals(AgentPoxyLevelEnum.LEVEL_ONE.getDescription())) {
                        System.out.println(AgentPoxyLevelEnum.LEVEL_ONE.getDescription());
//                        return AjaxResult.error("该用户已经是代理");
                        return AjaxResult.error("该用户已经是" + AgentPoxyLevelEnum.LEVEL_ONE.getDescription() + "代理");
                    }
                    if (s.equals(AgentPoxyLevelEnum.LEVEL_TWO.getDescription())) {
                        System.out.println(AgentPoxyLevelEnum.LEVEL_TWO.getDescription());
//                        return AjaxResult.error("该用户已经是代理");
                        return AjaxResult.error("该用户已经是" + AgentPoxyLevelEnum.LEVEL_TWO.getDescription() + "代理");
                    }
                    if (s.equals(LEVEL_THREE.getDescription())) {
                        System.out.println(LEVEL_THREE.getDescription());
//                        return AjaxResult.error("该用户已经是代理");
                        return AjaxResult.error("该用户已经是" + LEVEL_THREE.getDescription() + "代理");
                    }
                }
            }

            CAgentRelations agentRelations = agentRelationsService.selectCAgentRelationsByAgentId(agentId);
            Assert.notNull(agentRelations, "代理信息不存在");
            Assert.notNull(agentRelations.getIsDelete() == 1, "代理信息不存在");
            if (agentRelations.getSuperUserId() != superiorId)
                return AjaxResult.error("只能向自己的上级申请！");

            //拿到上级代理信息
            CAgentRelations agentRelation = new CAgentRelations();
            agentRelation.setUserId(superiorId);
            List<CAgentRelations> cAgentRelations = agentRelationsService.selectCAgentRelationsList(agentRelation);
            Assert.notNull(cAgentRelations, "上级代理信息不存在");
            CAgentRelations agentRelation1 = cAgentRelations.get(0);


            //判断是否已经申请过
            boolean apply = agentCache.isApply(superiorId, userId, agentRelation1.getAgentId());
            if (apply)
                return AjaxResult.error("该用户已经申请过了");
            agentCache.cacheAgentApply(superiorId, userId, agentRelation1.getAgentId());
            return AjaxResult.success("申请成功");
        }

        return AjaxResult.error("该用户还没有资质成为代理");
    }

    /**
     * 查看我的下级申请
     *
     * @param userId
     * @return
     */
    @ApiOperation("查看我的下级申请")
    @GetMapping("/getMyApply")
    public AjaxResult getMyApply(@ApiParam(value = "用户id", required = true) Integer userId) {
        Assert.notNull(userId, "用户id不能为空");
        CUser cUser = userService.selectCUserByUserId(userId);
        Assert.notNull(cUser, "用户信息不存在");
        List<CUser> cUsers = new ArrayList<>();
        List<Object> agentApply = agentCache.getAgentApply(userId);
        List<AjaxResult> results = new ArrayList<>();
        System.out.println("agentApply======================" + agentApply);
        if (agentApply.size() == 0)
            return AjaxResult.success("暂无申请");
        for (Object o : agentApply) {
            System.out.println("1111======================" + o);
            for (Object o1 : (List) o) {
                System.out.println("2222======================" + o1);
                CUser user = userService.selectCUserByUserId(Integer.valueOf(o1.toString()));
                //查看我的代理信息
                CAgentRelations agentRelation = new CAgentRelations();
                agentRelation.setUserId(user.getUserId());
                agentRelation.setIsDelete(0);
                AjaxResult ajaxResult = new AjaxResult();
                if (user != null)
                    ajaxResult.put("cUsers", user);
                else
                    continue;
                List<CAgentRelations> cAgentRelations = agentRelationsService.selectCAgentRelationsList(agentRelation);
                if (!cAgentRelations.isEmpty())
                    ajaxResult.put("agentId",cAgentRelations.get(0).getAgentId());
                System.out.println("3333======================" + user);
                results.add(ajaxResult);
            }
        }
        return AjaxResult.success(results);
    }

    //    审批
    @ApiOperation("审批")
    @PostMapping("/approval")
    public AjaxResult approval(@ApiParam(value = "申请者用户id", required = true) Integer userId,
                               @ApiParam(value = "下级代理关系id", required = true) Integer agentId,
                               @ApiParam(value = "审批结果", required = true) Integer result) {
        Assert.notNull(userId, "用户id不能为空");
        Assert.notNull(result, "审批结果不能为空");
        CUser cUser = userService.selectCUserByUserId(userId);
        Assert.notNull(cUser, "用户信息不存在");
        CAgentRelations agentRelations = agentRelationsService.selectCAgentRelationsByAgentId(agentId);
        Assert.notNull(agentRelations, "代理信息不存在");
        Assert.isTrue(agentRelations.getIsDelete() == 0, "代理信息不存在");
        if (!agentRelations.getAgentLevel().equals(NEW_USER.getDescription()))
            return AjaxResult.error("该用户已经是代理");

//拿到上级代理信息
        CAgentRelations agentRelation = new CAgentRelations();
        agentRelation.setUserId(agentRelations.getSuperUserId());
        List<CAgentRelations> cAgentRelations = agentRelationsService.selectCAgentRelationsList(agentRelation);
        Assert.notNull(cAgentRelations, "上级代理信息不存在");
        CAgentRelations agentRelation1 = cAgentRelations.get(0);

        if (result == 1) {
            String level = agentRelation1.getAgentLevel();
            String s = YqmGenerate(String.valueOf(userId), "yqm");
            agentRelations.setQrCode(s);
            if (level.equals(NEW_USER.getDescription()))
                agentRelations.setAgentLevel(NEW_USER.getDescription());
            else if (level.equals(LEVEL_THREE.getDescription()))
                agentRelations.setAgentLevel(NEW_USER.getDescription());
            else if (level.equals(LEVEL_TWO.getDescription()))
                agentRelations.setAgentLevel(LEVEL_THREE.getDescription());
            else if (level.equals(LEVEL_ONE.getDescription()))
                agentRelations.setAgentLevel(LEVEL_TWO.getDescription());
            agentRelationsService.updateCAgentRelations(agentRelations);
            //删除redis中的申请信息
            agentCache.removeUserFromAgentApply(agentRelations.getSuperUserId(), userId, agentRelation1.getAgentId());
            return AjaxResult.success("审批通过");
        } else {
            //审批不通过
            return AjaxResult.success("审批不通过");
        }
    }

    //查看我邀请的用户
    @ApiOperation("查看我邀请的用户")
    @GetMapping("/getMyInvited")
    public AjaxResult getMyInvited(@ApiParam(value = "用户id", required = true) Integer userId,
                                   @ApiParam(value = "pageNum", required = true) Integer pageNum,
                                   @ApiParam(value = "pageSize", required = true) Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        Assert.notNull(userId, "用户id不能为空");
        CUser cUser = userService.selectCUserByUserId(userId);
        Assert.notNull(cUser, "用户信息不存在");
        CAgentRelations agentRelation = new CAgentRelations();
        agentRelation.setSuperUserId(userId);
        agentRelation.setIsDelete(0);
        List<CAgentRelations> cAgentRelations = agentRelationsService.selectCAgentRelationsList(agentRelation);
        List<AjaxResult> results = new ArrayList<>();
        if (cAgentRelations.size() == 0)
            return AjaxResult.success("暂无邀请");
        for (CAgentRelations agentUser : cAgentRelations) {
            CUser user = userService.selectCUserByUserId(agentUser.getUserId());
            if (user != null) {
                if (agentUser.getUserId() == userId)
                    continue;
                AjaxResult ajaxResult = new AjaxResult();
                ajaxResult.put("userId", user.getUserId());
                ajaxResult.put("agentId", agentUser.getAgentId());
                ajaxResult.put("userNick", user.getUserNick());
                ajaxResult.put("userPhone", user.getUserPhone());
                ajaxResult.put("userHeader", user.getUserHeader());
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                ajaxResult.put("createTime", formatter.format(user.getCreateTime()));
                ajaxResult.put("QRCode", agentUser.getQrCode());
                results.add(ajaxResult);
            }
        }
        return AjaxResult.success(results);
    }

    //查看个人邀请码
    @ApiOperation("查看个人代理信息")
    @GetMapping("/getMyAgencyDetail")
    public AjaxResult getMyYqm(@ApiParam(value = "用户id", required = true) Integer userId) {
        Assert.notNull(userId, "用户id不能为空");
        CUser cUser = userService.selectCUserByUserId(userId);
        Assert.notNull(cUser, "用户信息不存在");

        AjaxResult ajaxResult = new AjaxResult();
        CAgentRelations agentRelation = new CAgentRelations();
        agentRelation.setUserId(userId);
        List<CAgentRelations> cAgentRelations = agentRelationsService.selectCAgentRelationsList(agentRelation);
        Assert.notNull(cAgentRelations, "代理信息不存在");

        AjaxResult Result1 = new AjaxResult();
        Result1.put("userId", cUser.getUserId());
        Result1.put("agentId", cAgentRelations.get(0).getAgentId());
        Result1.put("superId", cAgentRelations.get(0).getSuperUserId());
        Result1.put("userNick", cUser.getUserNick());
        Result1.put("agentLevel", cAgentRelations.get(0).getAgentLevel());
        Result1.put("userPhone", cUser.getUserPhone());
        Result1.put("userHeader", cUser.getUserHeader());
        Result1.put("createTime", cUser.getCreateTime());
        Result1.put("MyQRCode", cAgentRelations.get(0).getQrCode());
        return AjaxResult.success(Result1);

    }
}
